/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Utils;

/**
 *
 * @author Tomasz Nowak
 */
public class ByteArrayConverter
{
	static public String toString( byte[] bytes )
	{
		return toString(bytes, 0, bytes.length);
	}

	static public String toString( byte[] bytes, int offset, int length )
	{
		StringBuilder sb = new StringBuilder();
		for ( int i = 0; i < length; ++i )
		{
			appendByte(bytes[i + offset], sb);
		}
		return sb.toString();
	}

	public static String bufferToHex( byte[] buffer )
	{
		StringBuilder sb = new StringBuilder();
		for ( byte oneByte: buffer )
		{
			appendByte(oneByte, sb);
		}
		return sb.toString();
	}

	private static StringBuilder appendByte( byte _byte, StringBuilder sb )
	{
		if ( _byte >= 0 )
		{
			return appendInt(_byte, sb);
		}
		else
		{
			return appendInt(( int ) (_byte + 256), sb);
		}
	}

	private static StringBuilder appendInt( int intValue, StringBuilder sb ) throws IllegalArgumentException
	{
		if ( intValue > 255 || intValue < 0 )
		{
			throw new IllegalArgumentException("intValue");
		}
		char second = intToHexNumber(intValue % 16);
		char first = intToHexNumber((intValue % 256 >> 4));
		sb.append(first);
		sb.append(second);
		return sb;
	}

	private static char intToHexNumber( int intValue )
	{
		if ( intValue < 10 )
		{
			return ( char ) ('0' + intValue);
		}
		else
		{
			return ( char ) ('A' + intValue - 10);
		}
	}
}
